package com.bruce.controller;

import com.bruce.bean.Colleage;
import com.bruce.bean.Course;
import com.bruce.bean.Major;
import com.bruce.service.collegeService;
import com.bruce.service.impl.collegeServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author cc
 * @date 2021/7/20 17:53
 * @Description
 */
@WebServlet("/collegeServlet.do")
public class CollegeServlet extends HttpServlet {
    collegeService collegeService = new collegeServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("flag");
        switch (method){
            case "getColleges":
                List<Colleage> colleges = collegeService.findColleges();
                Gson gson = new Gson();
                String s = gson.toJson(colleges);
                resp.getWriter().write(s);
                break;
            case "add":
                String cid = req.getParameter("cid");
                String cname = req.getParameter("cname");
                String cintroduction = req.getParameter("cintroduction");
                String type = req.getParameter("type");
                String belongcoll = req.getParameter("belongcoll");
                String belongpro = req.getParameter("belongpro");
                Course course = new Course(cid,cname,cintroduction,type,belongcoll,belongpro);
                try {
                    collegeService.insertCourse(course);
                }catch (RuntimeException e){
                    resp.getWriter().write("<script>alert('新增课程失败');location.href='/admin/addCourse.jsp';</script>");
                }
                 resp.getWriter().write("<script>alert('新增课程成功');location.href='/admin/addCourse.jsp';</script>");
                break;
        }
//        if ("getColleges".equals(method)){
// List<Colleage> colleges = collegeService.findColleges();
//                Gson gson = new Gson();
//                String s = gson.toJson(colleges);
//                resp.getWriter().write(s);
//
//        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
